<?php

/**
 * 店铺前台控制器
 * @author ezhu <ezhu@jipukeji.com>
 * @version 1.0
 */

namespace Home\Controller;

class StoreController extends HomeController{
    
    
    /**
     * 店铺首页
     */
    public function index(){

        $store_id = I('store_id');
        $map['store_id'] = $store_id;
        $map['status'] = 1;
        $data = M('Store')->where($map)->find();
        if(empty($data)){
            $this->error('店铺已关闭！');
        }
        // 店铺销售分类
        $sellCategory = M('storeSellCategory')->where(array('store_id'=>$store_id))->select();
        $sellIds = array();
        foreach ($sellCategory as $key=>$val){
            $sellIds[] = $val['sell_cid_1'];
        }
        $sellMap = array();
        $sellField = 'id,pid,name,sort,status';
        if(!empty($sellIds)){
            $sellMap['id'] = array('in',$sellIds);
            $sellMap['pid'] = array('eq',0);
            $selist = M('StoreClass')->field($sellField)->where(array('store_id' => $store_id,'pid'=>array('gt',0)))->limit(8)->order('pid desc ,sort DESC')->select();
        }

        // 店铺分类
        $class = M('StoreClass')->where(array('status'=>1,'store_id'=>$store_id))->select();
        
        //店铺导航
        $navMap['store_id'] = $store_id;
        $navMap['is_show'] = 1;
        $nav = M('StoreNav')->where($navMap)->limit(10)->field('id,title,url,new_open')->order('`sort` DESC')->select();
      
        $slide_url = explode(',',$data['slide_url']);
        $map1['store_id'] = $store_id;
        $map1['status'] = 1;
        $map1['type'] = 1;
        $order='sort ASC';
        $slide = M('StoreBanner')->where($map1)->field('slide')->order($order)->select();
        $slide_url = M('StoreBanner')->where($map1)->field('slide_url')->select();
        $map2['store_id'] = $store_id;
        $map2['status'] = 1;
        $map2['type'] = 2;
        $slides = M('StoreBanner')->where($map2)->field('slide')->order($order)->select();
        $slides_url = M('StoreBanner')->where($map2)->field('slide_url')->select();

        $slideList = array();
        foreach ($slide as $key=>$val){
            if(!empty($val)){
                $slideList[$key]['slide'] = $val['slide'];
                $slideList[$key]['url'] = $slide_url[$key]['slide_url'];
            }
        }

        $slideLists = array();
        foreach ($slides as $key=>$val){
            if(!empty($val)){
                $slideLists[$key]['slides'] = $val['slide'];
                $slideLists[$key]['urls'] = $slides_url[$key]['slide_url'];
            }
        }


        if(C('START_POSITION') && session('zone.id')){
            $city = session('zone.district') ? session('zone.district') : session('zone.id');
            $iteMap['_string'] = $where['_string'] = 'FIND_IN_SET("'.$city.'" , set_zone)';
        }
        // 热卖推荐读取，不够的读取首页推荐的
        $hOrder = '`is_hot` DESC,`is_recommend` DESC';
        $where['store_id'] = $store_id ; 
        $where['status'] = 1;
        $hotList = M('Item')->where($where)->order($hOrder)->limit(9)->select();
        $hot_num = count($hotList);
        // 所有商品
        $field = 'id, cid_1, name, subname, summary, price, mprice, buynum, is_top, sort, is_recommend, is_hot, is_promote, thumb, status';
        $order = '`is_top` DESC, `sort` ASC';
        $total = 6;
        $item_model = D('Item');
        $iteMap['store_id'] = $store_id;
        $iteMap['status'] = 1;
        $item_lists = $item_model->lists($iteMap, $field, $order, $total);
        
        $this->assign('selist', $selist);
        $this->assign('item_lists',$item_lists);
        $this->assign('class',$class);
        $this->assign('slideList',$slideList);
        $this->assign('slideLists',$slideLists);
        $this->assign('hotList',$hotList);
        $this->assign('hot_num',$hot_num);
        $this->assign('store_id',$store_id);
        $this->assign('data',$data);
        $this->assign('nav',$nav);
        $this->store_id = $store_id;
        $this->display();
        
    }

    /**
     * 商品列表
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    public function itemLists(){

        // 所有商品
        $store_id = I('store_id');
        $field = 'id, cid_1, name, subname, summary, price, mprice, buynum, is_top, sort, is_recommend, is_hot, is_promote, thumb, status';
        $order = '`is_top` DESC, `sort` ASC';
        $total = 4;
        $item_model = D('Item');
        $iteMap['store_id'] = $store_id;
        $iteMap['status'] = 1;


        $item_lists = $item_model->lists($iteMap, $field, $order, $total);


        $this->assign('item_lists',$item_lists);
        $this->display();
    }

    /**
     * 异步请求商品列表
     */
    public function ajaxItem(){
        
    }

    /**
     * 搜索
     * @author buddha <[email address]>
     * @param  string $cid     [description]
     * @param  string $label   [description]
     * @param  string $keyword [description]
     * @param  string $_field  [description]
     * @param  string $_order  [description]
     * @return [type]          [description]
     */
    public function search($cid = '', $label = '', $keyword = '', $_field = '', $_order = ''){
        $brand = I('get.brand','');
        $prop  = I('get.prop','');
        $cid = I('get.cid');
        $store_id = I('get.store_id');
        $item_labels = I('get.item_label');
        $searchArr = array();
        $where = array('status' => 1);
        //实例化数据模型
        $item_model = M('Item');
        $item_category_model = D('ItemCategory');
        $Store_class_model = D('StoreClass');
        $search_model = D('Search');
        $fav_model = D('Fav');
        $item_label = D('ItemLabel');
        $coupon=I('get.coupon');
        if($coupon){
            $cp=M('coupon')->find($coupon);
            if(!empty($cp['items'])){
                $where['id']=array('in',explode(',',$cp['items']));
            }
        }
        if(!empty($prop)){
            $getProp = explode(',',$prop);
            $selectProp = array();
            $propIds = array();
            foreach ($getProp as $proVal){
                $tmpPro = explode(':',$proVal);
                array_push($selectProp,$tmpPro['0']);
                array_push($propIds,$tmpPro['1']);
            }
            $selectProp = getUniqure($selectProp);
            $propIds = getUniqure($propIds);
            if($propIds){
                $option = M('PropertyOption')->where(array('id'=>array('in',$propIds)))->select();
                $prp_codes = array_column($option,'code');
                $prp_ids = array_column($option,'prp_id');
                if(!empty($prp_ids) && !empty($prp_codes)){
                    $mapArr = array();
                    foreach ($prp_codes as $codeK=>$codeV){
                        $mapArr[] = '%'.$codeV.'%';
                    }
                    $specMap['spc_code'] = array('like',$mapArr,'AND');
                    $specList = M('ItemSpecifiction')->where($specMap)->select();
                    $itemIds = array_column($specList,'item_id');
                    if(!empty($itemIds)){
                        $where['id']=array('in',$itemIds);
                    }

                    // 规格
                    $spec = M('ItemProperty')->where(array('id'=>array('in',$prp_ids),'type'=>'specification'))->select();
                    $spec = arrKeyChange($spec, 'id');
                    foreach ($option as $opk=>$opv){
                        $tmpArr['string'] = $spec[$opv['prp_id']]['cname'].'：'.$opv['option'];
                        $tmpArr['type'] = 'prop';
                        $tmpArr['param'] = '';
                        $tmpStr = $opv['prp_id'].':'.$opv['id'];
                        if(in_array($tmpStr,$getProp) && count($getProp) > 1){
                            foreach ($getProp as $proVal){
                                $tmpPro = explode(':',$proVal);
                                array_push($selectProp,$tmpPro['0']);
                                array_push($propIds,$tmpPro['1']);
                                if($tmpStr != $proVal){
                                    $tmpArr['param'] .= empty($tmpArr['param']) ? $proVal : ','.$proVal;
                                }
                            }
                        }
                        array_push($searchArr,$tmpArr);
                    }
                }
            }
        }
        //设置查询条件：商品分类
        $item_property = array();
        if($store_id){
            $where['store_id'] = $store_id;
        }
        if($cid){
            $store_pid = M('store_class')->where("id={$cid} and store_id={$store_id}")->getField('pid');
            if($store_pid == 0){
                $result = M('store_class')->where("pid={$cid} and store_id={$store_id}")->field('id')->select();
                $in_data = array();
                foreach($result as $val){
                    $in_data[] = $val['id'];
                }
                if(!empty($in_data)){
                    array_push($in_data,$cid);
                    $where['store_cid'] = array('in',$in_data);
                }else{
                    $where['store_cid'] = $cid;
                }
            }else{
                $where['store_cid'] = $cid;
            }
            $data_category = $item_category_model->info($cid);
            $meta_title = $data_category['meta_title'];
            // 查询规格
            $proMap['cid'] = $cid;
            $proMap['type'] = 'specification';
            $proMap['is_recommend'] = 1;
            // 规格：单选、复选、下拉框才可以展示，文本框不展示
            $proMap['formtype'] = array('in',array('radio','checkbox','select','image'));
            if(!empty($selectProp)){
                $proMap['id'] = array('not in',$selectProp);
            }
            $item_property = M('ItemProperty')->where($proMap)->select();
            foreach($item_property as $key=>$val){
                $optMap['prp_id'] = $val['id'];
                $item_property[$key]['option'] = M('PropertyOption')->where($optMap)->order('`sort` DESC')->select();
                if(!empty($item_property[$key]['option'])){
                    foreach ($item_property[$key]['option'] as $keys=>$vals){
                        if(!empty($prop) && $prop != $vals['id']){
                            $item_property[$key]['option'][$keys]['opt_ids'] = $prop.','.$val['id'].':'.$vals['id'];
                        }else{
                            $item_property[$key]['option'][$keys]['opt_ids'] = $val['id'].':'.$vals['id'];
                        }
                    }
                }
            }

            // 分类品牌读取
            $bMap['status'] = 1;
            $bMap['cid'] = $cid;
            $bOrder = '`recommend` DESC, `sort` DESC';
            $brandList = M('Brand')->where($bMap)->order($bOrder)->select();

            //获取标签
            $itemLabel = $item_label->getLabel($cid);
            $this->itemLabel = $itemLabel;
            $cate_active['item_label'][$item_labels] = 'current';

        }else{
            // 所有品牌读取
            $bMap['status'] = 1;
            $bOrder = '`recommend` DESC, `sort` DESC';
            $brandList = M('Brand')->where($bMap)->order($bOrder)->select();
        }

        if(!empty($brand)){
            $brandIds = explode(',',$brand);
            $where['brand_id']=array('in',$brandIds);
            // 查询品牌
            $brandMap['status'] = 1;
            $brandMap['id'] = array('in',$brandIds);
            $brandSearch = M('Brand')->where($brandMap)->select();
            $tmpBrand['string'] = '品牌：';
            $tmpBrand['type'] = 'brand';
            $tmpBrand['param'] = '';
            $brandCount = count($brandSearch);
            foreach ($brandSearch as $bKey=>$bVal){
                $tmpBrand['string'] .= ($brandCount-1 > $bKey) ? $bVal['name'].'、' : $bVal['name'];
            }
            array_push($searchArr,$tmpBrand);
        }

        //设置查询条件：商品标注&标签&特征
        //（is_recommend->首页推荐，is_new->新品，is_hot->热卖，is_promote->特价）
        if($label){
            $label_key = array(
                'index' => array('is_recommend', '推荐'),
                'new' => array('is_new', '新品'),
                'hot' => array('is_hot', '热卖'),
                'promote' => array('is_promote', '特价')
            );
            if($res = $label_key[$label]){
                $where[$res[0]] = 1;
                $meta_title = $res[1];
            }
        }

        //设置查询条件：查询关键词
        /*      if($keyword){
              $has_keyword = $search_model->hasKeyword($keyword);
                  if($has_keyword){
                $map['keyword'] = $has_keyword['keyword'];
                $search_model->where($map)->setInc('num');
                $where['id'] = array('IN', $has_keyword['result']);
              }else{
                $where['name'] = array('LIKE', '%'.$keyword.'%');
              }
              $meta_title = $keyword;
            }*/

        $meta_title = $keyword;
        $where['name'] = array('LIKE', '%'.$keyword.'%');
        //如果有商品标签
        if($item_labels){
            $where['_string'] = 'FIND_IN_SET("'.$item_labels.'" , item_label)';
        }

        //根据查询条件查询商品数据
        $order = '`is_top` desc, `sort` asc, `id` desc';
        if(I('get._field'))$order='`'.I('get._field').'` '.I('get._order').', '.$order;
        if(C('START_POSITION') && session('zone.id')){
            $city = session('zone.district') ? session('zone.district') : session('zone.id');
            $where['_string'] = 'FIND_IN_SET("'.$city.'" , set_zone)';
        }
        $lists = $this->lists($item_model, $where, $order, true, 24);
        //搜索结果加入索引
        //2015071114 Justin 增加过滤空关键字和空结果集 delete from jipu_search where keyword = '' or result=''
        if($keyword && !$has_keyword && $lists){
            $item_ids = get_sub_by_key($lists, 'id', '', true);
            //搜索结果加入索引
            $data = array(
                'keyword' => $keyword,
                'result' => $item_ids,
                'num' => 1,
            );
            $search_model->update($data);
        }

        //获取分类数据
        if(empty($cid))$cid=0;

        //获取当前类所在层级
        $cates[]=array('item'=>$Store_class_model->getChild($cid),'pid'=>$cid,'cid'=>0);
        $cate_active[$cid][0] = 'current';

        if(count($cates[0]['item'])==0)$cates=array();
        $pid=$cid;
        while($pid>0){
            $item_info=$Store_class_model->info($pid);
            $item_tmp=$Store_class_model->getBrother($pid);
            $cate_active[$item_tmp[0]['pid']][$pid] = 'current';
            $cates[]=array('item'=>$item_tmp,'cid'=>$pid,'cname'=>$item_info['name'],'pid'=>$item_tmp[0]['pid']);
            $pid=$item_tmp[0]['pid'];
        }
        $cates=array_reverse($cates);
        foreach($cates[0]['item'] as $key => $value){
            if($value['store_id'] != $store_id){
                unset($cates[0]['item'][$key]);
            }
        }

        //设置当前排序条件的活动样式
        $order_css['active'][I('get._field')][I('get._order')] = 'active';

        //获取当前用户收藏商品数据和封面图片路径
        $fav_list = $fav_model->listUserFav(UID, 'item');
        if($lists && is_array($lists)){
            foreach($lists as $key => &$value){
                if($value['thumb']){
                    $value['cover_path'] = get_cover($value['thumb'], 'path');
                }
                if(!$value['buynum']){
                    $value['buynum'] = 0;
                }

                //判断收藏状态
                if($fav_list && is_array($fav_list)){
                    $value['is_fav'] = (in_array($value['id'], $fav_list)) ? 1 : 0;
                }else{
                    $value['is_fav'] = 0;
                }
            }
        }
        //记录当前页面URL地址Cookie
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        //模板输出变量赋值
        $this->category = $cates;
        //var_dump($cates);
        $this->show_child=1;
        $this->cateTree=$item_category_model->getTree();
        $this->assign('brandList',$brandList);
        $this->assign('searchArr',$searchArr);
        $this->cate_active = $cate_active;
        $this->cid = $cid;
        $this->brand = $brand;
        $this->prop = $prop;
        $this->label = $label;
        $this->keyword = $keyword;
        $this->_field = $_field;
        $this->_order = $_order;
        $this->order = $order;
        $this->lists = $lists;
        $this->order_css = $order_css;
        $this->meta_title = $meta_title;
        $this->item_label = $item_labels;
        $this->store_id = $store_id;
        $this->assign('item_property',$item_property);
        IS_AJAX ? $this->display('itemList') : $this->display();
    }

    /**
     * 
     * @author buddha <[email address]>
     * @return [type] [description]
     */
    public function brife(){
        $this->display();
    }


}